package cn.fanqinghong.ymcc.exception;

import cn.fanqinghong.ymcc.enumerror.GlobalError;
import cn.fanqinghong.ymcc.result.JSONResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * FAN
 * 2022/7/15  10:07
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public JSONResult exceptionHandler(Exception e){
        e.printStackTrace();
        if (e.getClass().getSimpleName().indexOf("AccessDeniedException") != -1){
            return JSONResult.error(
                    "没有权限访问",
                    "404"
            );
        }
        return JSONResult.error(
                GlobalError.BAD_REQUEST.getMessage(),
                GlobalError.BAD_REQUEST.getCode());
    }

    @ExceptionHandler(value = GlobalException.class)
    public JSONResult globalExceptionHandler(GlobalException e){
        e.printStackTrace();
        return JSONResult.error(e.getMessage(),e.getCode());
    }
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JSONResult methodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        StringBuilder sb = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(error ->{
            sb.append(error.getDefaultMessage()).append(";");
        });
        return JSONResult.error(sb.toString());
    }

}
